import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Button, Col, Row, Popover } from 'antd';
import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';
import PopImgShow from '@/components/PopImgShow';
import dayjs from 'dayjs';
import uploadOss from '@/utils/aliOssUpload';
import { categoryType_status } from '@/common/contact'
const PlanForm = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading, activeTabKey, categoryList } = props;
  const { show = false, detail = {} } = visible;
  const { id } = detail;
  useEffect(() => {
    if (show) {
      setUploadType(activeTabKey)
    }
    else {
      setData({});
    }
  }, [show]);
  const acceptData = {
    ebook: ',.pdf,.epub,',
    voice: ',.mp3,',
    document: ',.pptx,.ppt,.docx,.doc,.xls,.xlsx,.pdf,.csv,.xlsm,.txt,.zip,.vtt,',
  }[activeTabKey]
  function isValidExtension(filename) {
    // 正则解释：匹配以 .doc / .docx / .xls / .xlsx / .epub 结尾的字符串（不区分大小写）
    const pattern = /\.(docx?|xlsx?|pdf?|epub)$/i;
    return pattern.test(filename);
  }
  const [form] = Form.useForm();
  const [data, setData] = useState(detail);
  const [uploadType, setUploadType] = useState('');
  const filterList = (list) => {
    return list.map((item) => {
      const { categoryName: label, id: value, subMaterialCategoryList: children } = item;
      const localItem = {
        label,
        value,
        node: item['node'],
        children: children ? filterList(children) : undefined,
      };
      return localItem;
    });
  };
  const setMedioIdData = (item) => {
    return {
      bucket: 'gygj-resource',
      object: item.replace('https://resource.gy.cn/', ''),
      url: item,
    };
  };
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then(async (values) => {
      const { file } = data;
      const {
        contentType,
        cover,
        image,
        src,
        shiping,
        categoryId,
        source,
        materialType,
        materialName,
        otherFile,
        downloadFlag,
        shareFlag,
        description
      } = values;
      if (contentType === 'video') {
        let img = cover ? await uploadOss(cover) : await uploadOss(file);
        let video = await uploadOss(shiping, {}, 'video');
        let content = video.map((item) => {
          return setMedioIdData(item);
        });
        if (img) {
          img = img.map((item) => {
            return setMedioIdData(item);
          });
        }
        dispatch({
          type: 'liveStreaming/fakeHandleMaterial',
          payload: {
            id,
            cover: img[0] && JSON.stringify(img[0]),
            content: JSON.stringify(content[0]),
            categoryId: categoryId[categoryId.length - 1],
            materialName,
            contentType,
            downloadFlag,
            shareFlag,
            description
          },
          callback: () => {
            onClose();
            handleCallback();
          },
        });
      } else if (contentType === 'image') {
        let newImage = await uploadOss(image);
        let content = newImage.map((item) => {
          return setMedioIdData(item);
        });
        let img = cover ? await uploadOss(cover) : [];
        img = img.map((item) => {
          return setMedioIdData(item);
        })
        dispatch({
          type: 'liveStreaming/fakeHandleMaterial',
          payload: {
            id,
            content: JSON.stringify(content[0]),
            cover: img[0] ? JSON.stringify(img[0]) : '',
            categoryId: categoryId[categoryId.length - 1],
            contentType,
            materialName,
            downloadFlag,
            shareFlag,
            description
          },
          callback: () => {
            onClose();
            handleCallback();
          },
        });
      } else {
        let file = await uploadOss(otherFile);
        let content = file.map((item) => {
          return setMedioIdData(item);
        });
        dispatch({
          type: 'liveStreaming/fakeHandleMaterial',
          payload: {
            id,
            content: JSON.stringify(content[0]),
            categoryId: categoryId[categoryId.length - 1],
            contentType,
            materialName,
            downloadFlag,
            shareFlag,
            description
          },
          callback: () => {
            onClose();
            handleCallback();
          },
        });
      }
    });
  };


  // 我在hooks下写的
  const getVideoBase64 = (file) => {
    return new Promise(function (resolve) {
      let dataURL = URL.createObjectURL(file);
      const video = document.createElement('video');
      video.setAttribute('crossOrigin', 'anonymous'); // 处理跨域
      video.setAttribute('src', dataURL);
      video.setAttribute('preload', 'auto');
      video.addEventListener('loadeddata', function () {
        const canvas = document.createElement('canvas');
        const width = video.videoWidth || 400; // canvas的尺寸和图片一样
        const height = video.videoHeight || 240; // 设置默认宽高为  400  240
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(video, 0, 0, width, height); // 绘制canvas
        dataURL = canvas.toDataURL('image/jpeg'); // 转换为base64
        resolve(dataURL);
      });
    });
  };

  const dataURLtoFile = (dataurl, filename) => {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };

  const formItems = [
    {
      label: '内容类型',
      name: 'contentType',
      type: 'radio',
      disabled: true,
      select: categoryType_status,
    },
    {
      label: '视频',
      name: 'shiping',
      disabled: id,
      maxFile: 1,
      type: 'videoUpload',
      visible: uploadType === 'video',
      onRemove: () => {
        setData({});
      },
      onChange: (value) => {
        const { file, name } = value;
        form.setFieldValue('materialName', file.name)
        getVideoBase64(file).then((val) => {
          setData({
            src: val,
            file: dataURLtoFile(val, name),
          });
        });
      },
    },
    {
      label: '上传图片',
      disabled: id,
      name: 'image',
      visible: uploadType === 'image',
      maxFile: 1,
      type: 'upload',
      onChange: (e) => {
        const { file = {} } = e
        const { name = ''
        } = file
        form.setFieldValue('materialName', name.split('.')[0])
      },
    },
    {
      label: `上传${categoryType_status[activeTabKey]}`,
      disabled: id,
      name: 'otherFile',
      visible: uploadType !== 'image' && uploadType !== 'video',
      onChange: (e) => {
        const { file = {} } = e
        const { name = ''
        } = file
        form.setFieldValue('materialName', name.split('.')[0])
        if (isValidExtension(name) && activeTabKey === 'ebook') {
          form.setFieldValue('downloadFlag', '1')
        }
      },
      maxFile: 1,
      type: 'otherUpload',
      accept: acceptData,
      extra: '仅支持上传文件格式后缀为' + acceptData
    },
    {
      label: '设置封面',
      name: 'cover',
      maxFile: 1,
      visible: uploadType === 'image' || uploadType === 'video',
      type: 'upload',
      extra: data.src ? <PopImgShow url={data.src}>默认封面</PopImgShow> : null,
      rules: [{ required: false }],
    },
    {
      label: '素材名称',
      name: 'materialName',
    },
    {
      label: '分类',
      name: 'categoryId',
      type: 'cascader',
      changeOnSelect: true,
      select: filterList(categoryList),
    },
    {
      label: '能否分享',
      name: 'shareFlag',
      type: 'select',
      select: {
        0: '否',
        1: '是',
        2: '跟随分类'
      }
    },
    {
      label: '能否下载',
      name: 'downloadFlag',
      type: 'select',
      select: {
        0: '否',
        1: '是',
        2: '跟随分类'
      }
    },
    {
      label: '素材描述',
      name: 'description',
      type: 'textArea',
      rules: [{ required: false }],
    }
  ];

  const modalProps = {
    title: `${id ? '修改' : '新增'}`,
    visible: show,
    onClose,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        提交
      </Button>
    ),
  };

  return (
    <DrawerCondition {...modalProps}>
      <FormCondition form={form} formItems={formItems} initialValues={{
        ...detail,
        contentType: activeTabKey
      }}></FormCondition>
    </DrawerCondition>
  );
};

export default connect(({ loading }) => ({}))(PlanForm);
